package com.gemme.gemme.util;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSAuthCredentialsProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.OSSRequest;
import com.alibaba.sdk.android.oss.model.OSSResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.gemme.gemme.manager.DataManager;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MyOSSUtils {
    private static MyOSSUtils instance;

    private final String P_ENDPOINT ="http://oss-cn-hangzhou.aliyuncs.com";//主机地址（OSS文档中有提到）

//    private final String P_STSSERVER = "http://gemme.oss-cn-hangzhou.aliyuncs.com";//（服务器域名）
//    private final String P_STSSERVER = "http://192.168.1.7:9999/third/oss/appBaseOss";//（服务器域名）
    private final String P_STSSERVER = DataManager.BaseUrl +
        "third/oss/appBaseOss";//（服务器域名）  :9999/

    public static final String P_BUCKETNAME ="gemme";//（文件夹名字）

    private OSS oss;

    private SimpleDateFormat simpleDateFormat;

    public MyOSSUtils() {

    }

    public static MyOSSUtils getInstance() {

        if (instance ==null) {

            if (instance ==null) {

                return new MyOSSUtils();

            }

        }

        return instance;

    }

    private void getOSs(Context context) {

//推荐使用OSSAuthCredentialsProvider。token过期可以及时更新

//        OSSCredentialProvider credentialProvider =new OSSAuthCredentialsProvider(P_STSSERVER);
        OSSCredentialProvider credentialProvider =new MyOSSAuthCredentialsProvider(P_STSSERVER,context);

//该配置类如果不设置，会有默认配置，具体可看该类

        ClientConfiguration conf =new ClientConfiguration();

        conf.setConnectionTimeout(15 *1000);// 连接超时，默认15秒

        conf.setSocketTimeout(15 *1000);// socket超时，默认15秒

        conf.setMaxConcurrentRequest(5);// 最大并发请求数，默认5个

        conf.setMaxErrorRetry(2);// 失败后最大重试次数，默认2次

        oss =new OSSClient(context,P_ENDPOINT, credentialProvider);

        if (simpleDateFormat==null){

            simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd");

        }

    }

    public String getName(String imgPath){
        String objectName = "";
        try {
            long l = System.currentTimeMillis();
             objectName =  new File(imgPath).getName().replace(".",l+".");
            objectName = MyOSSUtils.getFileName(objectName, 2, 0);
        }catch (Exception e){

        }

        return objectName;
    }

    public void upImage1(Context context, String imgPath,final MyOSSUtils.OssUpCallback ossUpCallback){
        try {

            upImage(context,ossUpCallback,getName(imgPath),imgPath);
        }catch (Exception e){

        }

    }

    /**
     * 上传图片 上传文件
     *
     * @param context application上下文对象
     * @param ossUpCallback 成功的回调
     * @param img_name 上传到oss后的文件名称，图片要记得带后缀 如：.jpg
     * @param imgPath 图片的本地路径
     *
     */

    public void upImage(Context context, final MyOSSUtils.OssUpCallback ossUpCallback, final String img_name, String imgPath) {

        getOSs(context);

        final Date data =new Date();

        data.setTime(System.currentTimeMillis());

        PutObjectRequest putObjectRequest =new PutObjectRequest(P_BUCKETNAME,img_name, imgPath);

        putObjectRequest.setProgressCallback(new OSSProgressCallback() {

            @Override
            public void onProgress(Object request, long currentSize, long totalSize) {
                ossUpCallback.inProgress(currentSize, totalSize);
            }



        });

        oss.asyncPutObject(putObjectRequest,new OSSCompletedCallback() {

            @Override
            public void onSuccess(OSSRequest request, OSSResult result) {
                Log.e("MyOSSUtils","------getRequestId:" + result.getRequestId());
//                ossUpCallback.successImg(oss.presignPublicObjectURL(P_BUCKETNAME,simpleDateFormat.format(data)+"/"+img_name));
                ossUpCallback.successImg(oss.presignPublicObjectURL(P_BUCKETNAME,img_name));
            }

            @Override
            public void onFailure(OSSRequest request, ClientException clientException, ServiceException serviceException) {
                ossUpCallback.successImg(null);
            }


        });

    }

    /**
     * 上传图片 上传流
     *
     * @param context application上下文对象
     * @param ossUpCallback 成功的回调
     * @param img_name 上传到oss后的文件名称，图片要记得带后缀 如：.jpg
     * @param imgbyte 图片的byte数组
     */

    public void upImage(Context context, final MyOSSUtils.OssUpCallback ossUpCallback, final String img_name, byte[] imgbyte) {

        getOSs(context);

        final Date data =new Date();

        data.setTime(System.currentTimeMillis());

        PutObjectRequest putObjectRequest =new PutObjectRequest(P_BUCKETNAME,simpleDateFormat.format(data)+"/"+ img_name, imgbyte);

        putObjectRequest.setProgressCallback(new OSSProgressCallback() {

            @Override
            public void onProgress(Object request, long currentSize, long totalSize) {
                ossUpCallback.inProgress(currentSize, totalSize);
            }



        });

        oss.asyncPutObject(putObjectRequest,new OSSCompletedCallback() {

            @Override
            public void onSuccess(OSSRequest request, OSSResult result) {
                Log.e("MyOSSUtils","------getRequestId:" + result.getRequestId());

                ossUpCallback.successImg(oss.presignPublicObjectURL(P_BUCKETNAME,simpleDateFormat.format(data)+"/"+img_name));
            }

            @Override
            public void onFailure(OSSRequest request, ClientException clientException, ServiceException serviceException) {
                ossUpCallback.successImg(null);

            }



        });

    }

    /**
     * 上传视频
     *
     * @param context application上下文对象
     * @param ossUpCallback 成功的回调
     * @param video_name 上传到oss后的文件名称，视频要记得带后缀 如：.mp4
     * @param video_path 视频的本地路径
     */

    public void upVideo(Context context, final MyOSSUtils.OssUpCallback ossUpCallback, final String video_name, String video_path) {

        getOSs(context);

        final Date data =new Date();

        data.setTime(System.currentTimeMillis());
//"gemmeApp/"+ simpleDateFormat.format(data)+"/photo/"+  img_name
        PutObjectRequest putObjectRequest =new PutObjectRequest(P_BUCKETNAME,"gemmeApp/"+ simpleDateFormat.format(data)+"/video/"+ video_name, video_path);

        putObjectRequest.setProgressCallback(new OSSProgressCallback() {

            @Override
            public void onProgress(Object request, long currentSize, long totalSize) {
                ossUpCallback.inProgress(currentSize, totalSize);
            }

            /*@Override

            public void onProgress(PutObjectRequest request,long currentSize,long totalSize) {

                ossUpCallback.inProgress(currentSize, totalSize);

            }*/

        });

        oss.asyncPutObject(putObjectRequest,new OSSCompletedCallback() {

            @Override
            public void onSuccess(OSSRequest request, OSSResult result) {
                ossUpCallback.successVideo(oss.presignPublicObjectURL(P_BUCKETNAME,"gemmeApp/"+ simpleDateFormat.format(data)+"/video/"+ video_name));
            }

            @Override
            public void onFailure(OSSRequest request, ClientException clientException, ServiceException serviceException) {
                ossUpCallback.successVideo(null);

            }



        });

    }

    public interface OssUpCallback {

        void successImg(String img_url);

        void successVideo(String video_url);

        void inProgress(long progress, long zong);

    }




    //oss格式
/*    社区  gemmeApp/community/picture或者video/日期   0
    商城评价  gemmeApp/evaluate/picture或者video/日期   1
    头像   gemmeApp/headPortrait/日期                   2
picture  0
video 1

    gemmeApp/2020-08-23/photo/IMG_CMP_2418792831598165257489.jpeg
"gemmeApp/"+ simpleDateFormat.format(data)+"/photo/"+  img_name*/

    //得到生成的文件名称 社区  评价  头像
    public static final String getFileName(String objectName,int doamin_type,int filetype){
            String str = "";
            try {
                final Date data =new Date();
                data.setTime(System.currentTimeMillis());
                SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd");
//                str = "gemmeApp/"+ format.format(data)+"/photo/"+  objectName;
                String domain = "";
                String filetypeStr = "";
                switch (doamin_type){
                    case 0:
                        domain = "community";
                        break;
                    case 1:
                        domain = "evaluate";
                        break;
                    case 2:
                        domain = "headPortrait";
                        break;
                }

                switch (filetype){
                    case 0:
                        filetypeStr = "picture";
                        break;
                    case 1:
                        filetypeStr = "video";
                        break;

                }
//                gemmeApp/community/picture或者video/日期
                str = "gemmeApp/"+ domain + "/" + filetypeStr + "/" + format.format(data) + "/" + objectName ;

            }catch (Exception e){

            }

            return str;
    }


    //多图片上传
    public void upImageMuti(Context context,final List<String> urls,List<String> imageList,OnOssUploadListener onOssUploadListener) {
        if (urls.size() <= 0) {
            // 文件全部上传完毕，这里编写上传结束的逻辑，如果要在主线程操作，最好用Handler或runOnUiThead做对应逻辑
            return;// 这个return必须有，否则下面报越界异常，原因自己思考下哈
        }
        final String url = urls.get(0);
        if (TextUtils.isEmpty(url)) {
            urls.remove(0);
            // url为空就没必要上传了，这里做的是跳过它继续上传的逻辑。
            upImageMuti(context,urls,imageList,onOssUploadListener);
            return;
        }

        File file = new File(url);
        if (null == file || !file.exists()) {
            urls.remove(0);
            // 文件为空或不存在就没必要上传了，这里做的是跳过它继续上传的逻辑。
            upImageMuti(context,urls,imageList,onOssUploadListener);
            return;
        }
        if(oss == null)
        getOSs(context);

        final Date data =new Date();

        data.setTime(System.currentTimeMillis());
        String img_name = getName(url);
        PutObjectRequest putObjectRequest =new PutObjectRequest(P_BUCKETNAME,img_name, url);

        putObjectRequest.setProgressCallback(new OSSProgressCallback() {

            @Override
            public void onProgress(Object request, long currentSize, long totalSize) {
//                ossUpCallback.inProgress(currentSize, totalSize);
            }



        });

        oss.asyncPutObject(putObjectRequest,new OSSCompletedCallback() {

            @Override
            public void onSuccess(OSSRequest request, OSSResult result) {
                Log.e("MyOSSUtils","------getRequestId:" + result.getRequestId());
//                ossUpCallback.successImg(oss.presignPublicObjectURL(P_BUCKETNAME,simpleDateFormat.format(data)+"/"+img_name));
//                ossUpCallback.successImg(oss.presignPublicObjectURL(P_BUCKETNAME,img_name));
//                oss.presignPublicObjectURL(P_BUCKETNAME,getName(url));

                String imagePath = urls.remove(0);

                imageList.add(oss.presignPublicObjectURL(P_BUCKETNAME,img_name));
                if(urls.size() == 0){//上传结束
                    if(onOssUploadListener != null)
                        onOssUploadListener.onOssUploadListener(imageList);
                    return;
                }
                upImageMuti(context,urls,imageList,onOssUploadListener);// 递归同步效果
            }

            @Override
            public void onFailure(OSSRequest request, ClientException clientException, ServiceException serviceException) {
//                ossUpCallback.successImg(null);
                System.out.println("");
            }



        });
    }



    public interface OnOssUploadListener{
        void onOssUploadListener(List<String> imageList);
    }

}
